import CryptoJS from 'crypto-js'
import axios from "axios";

import areas from 'china-division/dist/areas.json';
import streets from 'china-division/dist/streets.json';
import villages from 'china-division/dist/villages.json';

const key = '46556a7340313736353448474a4b4b6e'
const iv = '48477479263625346f6a795579686779'

//加密
export function getDAes(data) {
    return getAesString(data, key, iv);
}

function getAesString(data, key, iv) {
    let keyUtf8 = CryptoJS.enc.Hex.parse(key);
    let ivUtf8 = CryptoJS.enc.Hex.parse(iv);
    //这个加密得到 不是字符串
    let encrypted = CryptoJS.AES.encrypt(data, keyUtf8, {
        iv: ivUtf8,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString();
}

// 解密
export function decryptDAes(encryptedData) {
    return getDAesString(encryptedData, key, iv);
}

function getDAesString(encryptedData, key, iv) {
    let keyUtf8 = CryptoJS.enc.Hex.parse(key);
    let ivUtf8 = CryptoJS.enc.Hex.parse(iv);
    let ciphertext = CryptoJS.enc.Hex.parse(encryptedData);

    // 解密
    let decrypted = CryptoJS.AES.decrypt({ciphertext: ciphertext}, keyUtf8, {
        iv: ivUtf8,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    // 将解密结果转换为字符串
    return decrypted.toString(CryptoJS.enc.Utf8);
}





/**
 * 根据身份证实现自动生成生日，性别，年龄
 * @param idEn
 * @param val
 */
export async function validIdentityNumber(idEn, val) {
    let sex = null;
    let birth = null;
    let myDate = new Date();
    let month = myDate.getMonth() + 1;
    let day = myDate.getDate();
    let age = 0;

    if (val === 18) {
        age = myDate.getFullYear() - idEn.substring(6, 10) - 1;
        sex = idEn.substring(16, 17);
        birth = idEn.substring(6, 10) + "-" + idEn.substring(10, 12) + "-" + idEn.substring(12, 14);
        if (idEn.substring(10, 12) < month || idEn.substring(10, 12) === month && idEn.substring(12, 14) <= day) age++;

    }
    if (val === 15) {
        age = myDate.getFullYear() - idEn.substring(6, 8) - 1901;
        sex = idEn.substring(13, 14);
        birth = "19" + idEn.substring(6, 8) + "-" + idEn.substring(8, 10) + "-" + idEn.substring(10, 12);
        if (idEn.substring(8, 10) < month || idEn.substring(8, 10) === month && idEn.substring(10, 12) <= day) age++;
    }
    //性别  ==> 1:男       0:女
    return {
        gender: sex % 2 === 0 ? 'F' : 'M',
        age: age,
        birthDate: birth
    }
}

/**
 * 简单的手机号验证正则表达式（不严谨）
 * @param phone
 * @returns {boolean}
 */
export function validatePhoneByLoose(phone) {
    const phonePattern = /^1[0-9]{10}$/; // 简单的手机号验证正则表达式
    return phonePattern.test(phone);
}

/**
 * 简单的手机号验证正则表达式（严谨的）
 * @param phone
 * @returns {boolean}
 */
export async function validatePhoneByRigor(phone) {
    const phonePattern = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    return phonePattern.test(phone)
}








// 获取上海所有的区、街道、社区
let shanghai_code = '31';
export let shanghai_area, shanghai_street, shanghai_village = []
// 上海所有区
// export const shanghai_area = get_china_division_formatData(areas.filter(area => area.provinceCode === shanghai_code));
//  fetchShanghaiArea('/json/shanghai_area.json').then(res => {
//     shanghai_area = res;
//     // console.log('shanghai_area', shanghai_area)
// })
// get_shanghai_area_axios(3).then(res => {
//     shanghai_area = res.data;
//     console.log('shanghai_area', shanghai_area)
// })
//  上海所有街道
// shanghai_street = get_china_division_formatData(streets.filter(street => street.provinceCode === shanghai_code));
// fetchShanghaiArea('/json/shanghai_street.json').then(res => {
//     shanghai_street = res;
//     // console.log('shanghai_street', shanghai_street)
// })

// get_shanghai_area_axios(4).then(res => {
//     shanghai_street = res.data;
//     console.log('shanghai_street', shanghai_street)
// })


//  上海所有社区
// shanghai_village = get_china_division_formatData(villages.filter(village => village.provinceCode === shanghai_code));
// fetchShanghaiArea('/json/shanghai_village.json').then(res => {
//     shanghai_village = res;
//     // console.log('shanghai_village', shanghai_village)
// })


// get_shanghai_area_axios(5).then(res => {
//     shanghai_village = res.data;
//     console.log('shanghai_village', shanghai_village)
// })

/**
 *  获取上海区域信息
 * @param level
 * @returns {AxiosPromise}
 */
export function get_shanghai_area_axios(level) {
    return axios({
        url: '/data/area/list',
        method: 'get',
        params:{
            level: level
        }
    })
}




// console.log('shanghai_area', shanghai_area)
// console.log('shanghai_street', shanghai_street)
// console.log('shanghai_village', shanghai_village)
export function get_china_division_formatData(flag, data) {
    return data.map(item => {
        return {
            areaId: item.areaId,
            areaName: item.areaName,
            parentId: item.parentId,
            level: item.level,
            remark: item.remark,
            leaf: flag,   // 设置叶子节点，确保没有右箭头
        };
    });
}


/**
 * 自动移除children字段
 * @param data
 * @returns {*}
 */
export function auto_remove_children_formatData(data) {
    return data.map(item => {
        const formattedItem = {
            code: item.code,
            name: item.name,
        };
        if (item.children && item.children.length > 0) {
            formattedItem.children = item.children;
        }
        return formattedItem;
    });
}

export function get_shanghai_division_by_levelAndCode(level, code) {
    let children = [];
    // console.log('level', level, 'code', code)
    switch (level) {
        case 1:
            children = get_china_division_formatData(false, shanghai_street.filter(street => street.parentId === code));
            break;
        case 2:
            children = get_china_division_formatData(true, shanghai_village.filter(village => village.parentId === code));
            break;
    }
    return children;
}


export function get_shanghai_division_by_levelAndCode2(level, code) {
    let children = [];
    // console.log('level', level, 'code', code)
    switch (level) {
        case 1:
            children = get_china_division_formatData(true, shanghai_street.filter(street => street.parentId === code));
            break;
    }
    return children;
}


// 执行保存 案例
// saveToFile(shanghai_street, 'shanghai_street.json')
/**
 * 函数用于保存数据到JSON文件
 * @param data
 * @param filename
 */
function saveToFile(data, filename) {
    const json = JSON.stringify(data);
    const blob = new Blob([json], {type: 'application/json'});
    saveAs(blob, filename);
}


/**
 * 从本地json文件中读取地区数据
 * @param path
 * @returns {Promise<any|null>}
 */
export async function fetchShanghaiArea(path) {
    try {
        const response = await axios.get(path);
        return response.data;
    } catch (error) {
        console.error('获取文件时出错：', error);
        return null;
    }
}











// 将文件转成base64编码
export function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

//hash获取url参数
export function getUrlParam(name) {
    let after = window.location.hash.split("?", 2)[1];
    const after2 = window.location.href.split("?", 2)[1];
    if (!after) after = after2
    if (after) {
        const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        const r = after.match(reg);
        if (r != null) {
            return decodeURIComponent(r[2]);
        } else {
            return false;
        }
    }
}

/**
 * 获取播放器配置
 * @returns {{playbackRates: number[], controls: boolean, sources: [{src: string, type: string},{src: string, type: string}], loop: boolean, aspectRatio: string, fluid: boolean, language: string, controlBar: {remainingTimeDisplay: boolean, timeDivider: boolean, fullscreenToggle: boolean, durationDisplay: boolean}, preload: string, poster: string, muted: boolean, autoplay: boolean}}
 */
export function getPlayerOptions() {
    return {
        autoplay: false,
        controls: true,
        preload: 'auto',
        poster: 'path_to_poster_image.jpg',
        muted: false,
        loop: false,
        aspectRatio: '16:9',
        fluid: true,
        playbackRates: [0.5, 1, 1.5, 2],
        language: 'en',
        sources: [
            {
                src: 'path_to_video.mp4',
                type: 'video/mp4'
            },
            {
                src: 'path_to_video.webm',
                type: 'video/webm'
            }
        ],
        controlBar: {
            timeDivider: true,
            durationDisplay: true,
            remainingTimeDisplay: false,
            fullscreenToggle: true
        }
    };
}


/**
 * 解析Bilibili视频链接中的视频ID
 * @param videoUrl
 * @returns {*|string}
 */
export function parseBilibiliVideoId(videoUrl) {
    // 先用正则表达式匹配视频ID
    const regex = /\/video\/([A-Za-z0-9]+)/;
    const match = videoUrl.match(regex);

    // 如果匹配到了视频ID，则返回匹配到的部分
    if (match && match.length > 1) {
        return match[1];
    }

    // 如果没有匹配到视频ID，则返回空字符串
    return '';
}


/**
 * 费用转换 分 转 元
 * @param cost
 * @returns {number|string}
 */
export function convert_cost(cost) {
    if (cost) {
        return parseFloat((cost / 100).toFixed(2)).toFixed(2);
    }
    return 0.00;
}


export function convert_cost2(cost) {
    if (cost) {
        return parseFloat((cost / 100).toFixed(2));
    }
    return 0.00;
}

/**
 * 软盘大小转换 MB 转 GB
 * @param size
 * @returns {number|*|string}
 */
export function convert_soft_size(size) {
    if (size) {
        if (size > 1024) return parseFloat((size / 1024).toFixed(2)).toFixed(2);
        return size
    }
    return 0.00;
}



